package fr.cpe.j2ee.projet.mdb;

import java.util.Date;
import java.util.HashMap;

import javax.ejb.ActivationConfigProperty;
import javax.ejb.EJB;
import javax.ejb.MessageDriven;
import javax.jms.JMSException;
import javax.jms.Message;
import javax.jms.MessageListener;
import javax.jms.ObjectMessage;

import fr.cpe.j2ee.projet.ejb.ConversationSession;
import fr.cpe.j2ee.projet.ejb.EmployeeSession;
import fr.cpe.j2ee.projet.ejb.MessageSession;
import fr.cpe.j2ee.projet.ejb.ProjectSession;

/**
 * Message-Driven Bean implementation class for: ChatMessages
 */
@MessageDriven(
		activationConfig = { @ActivationConfigProperty(
				propertyName = "destinationType", propertyValue = "javax.jms.Queue"), @ActivationConfigProperty(
				propertyName = "destination", propertyValue = "queue/chat")
		}, 
		mappedName = "chatQueue")
public class ChatMessages implements MessageListener {

	@EJB
	MessageSession messageSession;
	
    /**
     * Default constructor. 
     */
    public ChatMessages() {
    }
	
	/**
     * @see MessageListener#onMessage(Message)
     */
    public void onMessage(Message message) {
        if (message instanceof ObjectMessage) {
            System.out.println("Chat: TextMessage at " + new Date());
            ObjectMessage msg = (ObjectMessage) message;
            saveMessage(msg);
        } else {
            System.out.println("Not a valid message for this ChatQueue MDB");
        }
    }

	/**
	 * Create a new message
	 * @param msg Received message
	 */
	private void saveMessage(ObjectMessage msg) {
		try {
			fr.cpe.j2ee.projet.model.Message newMessage = (fr.cpe.j2ee.projet.model.Message) msg.getObject();
	        messageSession.createMsg(newMessage.getMesContent(), newMessage.getMesSendTime(), newMessage.getEmployee(), newMessage.getConversation());
	        System.out.println("message saved " + newMessage.getMesSendTime() + " : " + newMessage.getMesContent());
		} catch (JMSException e) {
            System.out.println("Saving Message Error");
			e.printStackTrace();
		}
	}

}
